<template>
  <div>
    <el-dialog
      :model-value="open"
      :close-on-click-modal="false"
      :title="title"
      width="780px"
      append-to-body
      :before-close="handleClose"
    >
      <el-form
        ref="editFormRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input
                v-model="form.noticeTitle"
                placeholder="请输入公告标题"
                clearable
                style="width: 80%;"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="noticeType">
              <el-select v-model="form.noticeType" filterable placeholder="请选择">
                <el-option
                  v-for="dict in dicts[DictDirection.通知公告]"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" placeholder="请选择部门">
              <el-select
                v-model="form.deptId"
                :disabled="form.recipientIds != undefined && form.recipientIds.length > 0"
                filterable
                clearable
              >
                <el-option
                  v-for="dept in dicts[DictDirection.部门列表]"
                  :key="dept.deptId"
                  :label="dept.deptName"
                  :value="dept.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工" placeholder="请选择员工">
              <el-select
                v-model="form.recipientIds"
                :disabled="form.deptId != undefined && form.deptId != ''"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="dict in dicts[DictDirection.员工]"
                  :key="dict.id"
                  :label="dict.nickName"
                  :value="dict.userName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dicts[DictDirection.通知状态]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <Editor v-model="form.noticeContent" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <template v-if="form.fileUrl && form.fileUrl.length > 0">
              <h3>已上传文件</h3>
              <ul class="fileList">
                <li v-for="item in form.fileUrl" :key="item.id">
                  <i class="el-icon-paperclip" style="color: blue;margin-right: 8px;"></i>
                  <a :href="item.url" :download="item.url">{{ item.name }}</a>
                  <el-button style="margin-left: 8px;" text @click="() => handleDelFile({ id: item.id, type: 'server' })">删除</el-button>
                </li>
              </ul>
            </template>
            <template v-if="fileList.length > 0">
              <h3>待上传文件</h3>
              <ul class="fileList">
                <li v-for="item in fileList" :key="item.uid">
                  <span>{{ item.name }}</span>
                  <el-button text @click="() => handleDelFile({ id: item.id, type: 'local' })">删除</el-button>
                </li>
              </ul>
            </template>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, defineExpose, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'

import useDicts, { DictDirection } from '@/store/modules/dicts'
import { getNotice, addNotice, updateNotice, delFile } from '@/api/system/announcements'

const dicts = useDicts()
dicts.setDicts(DictDirection.通知公告)
dicts.setDicts(DictDirection.通知状态)
dicts.setDicts(DictDirection.员工)
dicts.setDicts(DictDirection.部门列表)
const props = defineProps({
  title: {
    type: String,
  },
  open: {
    type: Boolean,
  },
})
const emit = defineEmits(['changeList', 'update:open'])
const editor = ref(null)

const
  // 新增表单显示
  form = ref({
    noticeId: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    status: undefined,
    noticeContent: undefined,
    fileUrl: undefined,
    deptId: undefined,
    recipientIds: [],
  }),

  // 规则
  rules = {
    noticeTitle: [{ required: true, message: '公告标题不能为空', trigger: 'bulr' }],
    noticeType: [{ required: true, message: '公告类型不能为空', trigger: 'blur' }],
  },
  editFormRef = ref(null),
  {
    proxy,
  }:{
   proxy:any
 } = getCurrentInstance()
// 重置表单
const reset = () => {
  form.value = {
    noticeId: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    status: undefined,
    noticeContent: undefined,
    fileUrl: undefined,
    deptId: undefined,
    recipientIds: [],
  }
  proxy.$resetForm(editFormRef.value)
}
// 获取修改
const getList = (id) => {
  getNotice(id).then(res => {
    form.value = res.data
  })
}

// const handleFileUpload = () => {
//   const file:HTMLElement = document.querySelector('.files.avatar-uploader.quill-file input')as HTMLElement
//   file.click()
// }
// const handleDelFile = ({ id, type }) => {
//   if (type === 'local') {
//     const fileList = proxy.$refs.fileUpload.uploadFiles
//     const index = fileList.findIndex(el => el.uid == id)
//     fileList.splice(index, 1)
//   } else if (type === 'server') {
//     ElMessageBox.confirm(`是否确认删除编号为"${ id }"的数据项?`, '警告', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     })
//     .then(() => delFile({ id: form.value.noticeId, uid: id }))
//     .then((res) => {
//       if (res.code === 200) {
//         const f = form.value.fileUrl
//         const inde = f.findIndex(el => el.id == id)
//         f.splice(inde, 1)
//       } else {
//         ElMessage.error(res.msg)
//       }
//     })
//     .catch((error) => {
//       if (error == 'cancel') {
//         ElMessage.info('取消删除')
//       }
//     })
//   }
// }
// 确定新增-修改
const submitForm = () => {
  proxy.$validateForm(editFormRef.value, () => {
    const formData = new FormData()
    formData.append('noticeStr', JSON.stringify(form.value))
    let res = null
    try {
      if (form.value.noticeId != undefined) {
        res = updateNotice(formData)
      } else {
        res = addNotice(formData)
      }
      if (res.code == 200) {
        if (form.value.noticeId != undefined) {
          ElMessage.success('更新成功')
          emit('changeList')
        } else {
          ElMessage.success('添加成功')
          emit('changeList')
        }
        cancel()
      }
    } catch (error) {
      console.log(error)
    }
  }) 
}
// 新增-删除取消
const cancel = () => {
  reset()
  emit('update:open', false)
}
const handleClose = () => {
  reset()
  emit('update:open', false)
}
defineExpose({
  getList,
})
</script>